<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" class="demo-form-inline" size="small">
        <el-form-item label>
          <el-select
            filterable
            placeholder="请选择门店"
            v-model="formInline.store_id"
            @change="storeChange"
          >
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label>
          <el-select v-model="formInline.warehouse" style="width:120px;" @change="warehouseChange">
            <el-option label="主仓" value="1"></el-option>
            <el-option label="中转仓" value="2"></el-option>
            <el-option label="机台仓" value="3"></el-option>
          </el-select>
          <el-select
            v-if="formInline.warehouse==2"
            v-model="formInline.house_id"
            style="width:120px;"
          >
            <el-option
              v-for="item in houseList"
              :key="item.house_id"
              :label="item.house_name"
              :value="item.house_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.conditions" style="width:140px;">
            <el-option label="搜礼品名称" value="3"></el-option>
            <el-option label="搜新礼品编号" value="1"></el-option>
            <el-option label="搜神采礼品编号" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.gift_no"
            placeholder="请输入编号/名称"
            style="width:160px;"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table
        highlight-current-row
        :data="list"
        v-loading.body="listLoading"
        border
        fit
        size="small"
        @sort-change="sortChange"
        ref="sort"
      >
        <el-table-column align="center" label="图片" width="80">
          <template slot-scope="scope">
            <vue-preview class="preview" :slides="scope.row.imgList"></vue-preview>
          </template>
        </el-table-column>
        <el-table-column v-if="warehouse==3" align="center" label="机台号" prop="machine_id"></el-table-column>
        <el-table-column align="center" label="新礼品编号" prop="gift_id"></el-table-column>
        <el-table-column align="center" label="神采礼品编号" prop="no_obsolete" sortable width="120"></el-table-column>
        <el-table-column align="center" label="礼品名称" prop="gift_name"></el-table-column>
        <el-table-column align="center" label="箱规" prop="box_num"></el-table-column>
        <el-table-column align="center" label="尺寸" prop="size"></el-table-column>
        <el-table-column align="center" label="分类" prop="type_name"></el-table-column>
        <!-- <el-table-column align="center" label="礼品详情">
                    <template slot-scope="scope">
                        <el-button type="text" @click="info(scope.$index)" size="mini">查看详情</el-button>
                    </template>
        </el-table-column>-->
        <el-table-column align="center" label="库存量" prop="num" sortable width="82"></el-table-column>
        <el-table-column align="center" label="实盘数">
          <template slot-scope="scope">
            <el-input
              :disabled="formInline.warehouse==3"
              v-model.number="scope.row.calibration_num"
              :ref="'input'+scope.$index"
              @keyup.enter.native="nextFocus(scope.$index)"
              placeholder="数量"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="盘点盈亏" sortable>
          <template slot-scope="scope">
            <span
              v-show="scope.row.calibration_num!==''"
              :class="scope.row.calibration_num*1-scope.row.num*1<0?'danger':'success'"
            >{{scope.row.calibration_num*1-scope.row.num*1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="在库时间(天)" prop="in_house_day" sortable></el-table-column>
        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            <el-input
              :disabled="formInline.warehouse==3"
              type="text"
              v-model="scope.row.remark"
              :ref="'inputR'+scope.$index"
              @keyup.enter.native="nextRFocus(scope.$index)"
              placeholder="备注"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <el-dialog :close-on-click-modal="false"  title="礼品详情" :visible.sync="infoDialog" width="600px">
            <el-table  highlight-current-row :data="giftInfo">
                <el-table-column align="center" prop="type_name_one" label="一级分类"> </el-table-column>
                <el-table-column align="center" prop="type_name_second" label="二级分类"></el-table-column>
                <el-table-column align="center" prop="type_name" label="三级分类"></el-table-column>
                <el-table-column align="center" prop="serie_name" label="系列"></el-table-column>
                <el-table-column align="center" prop="texture" label="材质"></el-table-column>
            </el-table>
    </el-dialog>-->
    <!-- 添加礼品弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="添加盘点礼品"
      :visible.sync="addGiftDialog"
      append-to-body
      width="600px"
    >
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input type="text" placeholder="输入礼品编号" v-model="search_gift_no" style="width:200px;"></el-input>
          <el-button type="primary" @click="searchGiftClick()">搜 索</el-button>
        </el-form-item>
      </el-form>
      <el-table highlight-current-row :data="searchGiftList" border>
        <el-table-column align="center" property="gift_name" label="礼品名称"></el-table-column>
        <el-table-column align="center" property="gift_id" label="新礼品编号"></el-table-column>
        <el-table-column align="center" property="no_obsolete" label="神采礼品编号"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveGiftClick()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <div class="pull-right">
        <el-button
          v-if="formInline.warehouse!=3"
          :disabled="list==null"
          type="primary"
          size="small"
          @click="addGiftClick"
        >添加盘点礼品</el-button>
        <el-button
          style="position:relative;overflow:hidden"
          :disabled="!formInline.store_id"
          v-if="formInline.warehouse!=3"
          type="primary"
          size="small"
        >
          <span>库存导入</span>
          <input
            :disabled="!formInline.store_id"
            style="opacity:0;z-index:999;width:100px;height:32px;position:absolute;top:0;left:0"
            type="file"
            ref="importInput"
            @change="importClick"
          />
        </el-button>
        <el-button
          :disabled="list==null||list.length==0"
          type="primary"
          size="small"
          @click="exportClick"
          :loading="exportLoading"
        >
          库存盘点表导出
          <count-down ref="cd" />
        </el-button>
        <el-button
          v-if="warehouse!=3"
          :disabled="no_check"
          type="primary"
          size="small"
          @click="saveClick(0)"
        >库存核准</el-button>
        <el-button
          :loading="is_save"
          v-if="warehouse!=3"
          :disabled="no_check||no_save"
          type="primary"
          size="small"
          @click="saveClick(1)"
        >{{is_save?'提交中':'提交保存'}}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getList,
  storeList,
  save,
  houseList,
  searchGift,
  getExport,
  // importForm,
} from "@/api/storage_control/inventory";
import Cookies from "js-cookie";
import axios from "axios";

export default {
  data() {
    return {
      exportLoading: false,
      is_save: false,
      fileList: [],
      warehouse: "",
      no_check: true,
      no_save: true,
      machineInfo: "",
      addGiftDialog: false,
      list: null,
      listLoading: false,
      searchGiftList: [],
      storeList: [],
      houseList: [],
      search_gift_no: "",
      formInline: {
        store_id: "",
        warehouse: "1",
        house_id: "",
        orderby: "",
        gift_no: "",
        conditions: "3",
      },
      saveForm: {
        store_id: "",
        warehouse: "",
        house_id: "",
        check_list: [],
      },
      infoText: "",
      url: "",
      giftInfo: [],
      infoDialog: false,
    };
  },
  created() {
    this.getStoreList();
  },
  methods: {
    sortChange(column, prop, order) {
      if (column.column && column.column.label == "盘点盈亏") {
        let ok = true;
        this.list.forEach((val) => {
          if (val.calibration_num == "" || val.calibration_num == null) {
            this.$refs.sort.columns[9].order = "";
            this.$message({
              type: "warning",
              message: "盘点盈亏排序仅在所有实盘数填完才能使用哦",
            });
            return (ok = false);
          }
        });
        if (ok) {
          this.list.sort((a, b) => {
            if (column.order == "ascending") {
              if (
                a.calibration_num * 1 - a.num * 1 <
                b.calibration_num * 1 - b.num * 1
              ) {
                return -1;
              }
              if (
                a.calibration_num * 1 - a.num * 1 >
                b.calibration_num * 1 - b.num * 1
              ) {
                return 1;
              }
              return 0;
            } else if (column.order == "descending") {
              if (
                a.calibration_num * 1 - a.num * 1 >
                b.calibration_num * 1 - b.num * 1
              ) {
                return -1;
              }
              if (
                a.calibration_num * 1 - a.num * 1 <
                b.calibration_num * 1 - b.num * 1
              ) {
                return 1;
              }
              return 0;
            }
          });
        }
      }
    },
    //导入功能  在请求头统一设置了data转换成后端需要的字符串，文件上传请求暂时写在VUE文件里
    importClick(e) {
      const that = this;
      console.log(
        e.target.files[0].name.substring(e.target.files[0].name.length - 3)
      );
      if (
        e.target.files[0].name.substring(e.target.files[0].name.length - 3) !=
        "csv"
      ) {
        that.$message({ type: "error", message: "请选择csv文件上传" });
        return;
      }
      let formData = new FormData();
      formData.append("store_id", this.formInline.store_id);
      formData.append(
        "house_id",
        this.formInline.warehouse == 2 ? this.formInline.house_id : ""
      );
      formData.append("check_csv", e.target.files[0]);
      let url = `https://${location.host}/smsi/index.php/Stock_check/back_csv`;
      let config = {
        headers: { didixueshengka: `${Cookies.get("SMS_AdminToken")}` },
      };
      axios.post(url, formData, config).then(function (response) {
        that.$message({
          type: response.data.code == 1 ? "success" : "error",
          message: response.data.message,
        });
        that.$refs.importInput.value = "";
        if (response.data.code == 1) {
          that.fetchData();
        }
      });
    },
    info(index) {
      this.giftInfo = [];
      this.infoDialog = true;
      this.giftInfo[0] = this.list[index];
    },
    nextFocus(index) {
      for (let i = 1; i < this.list.length; i++) {
        let focusIndex = index + i;
        let inputRef = "input" + focusIndex;
        if (this.$refs[inputRef]) {
          this.$refs[inputRef].$el.children[0].focus();
          return;
        }
      }
    },
    nextRFocus(index) {
      for (let i = 1; i < this.list.length; i++) {
        let focusIndex = index + i;
        let inputRef = "inputR" + focusIndex;
        if (this.$refs[inputRef]) {
          this.$refs[inputRef].$el.children[0].focus();
          return;
        }
      }
    },
    saveClick(type) {
      // console.log(this.list)
      let ok = true;
      for (let i = 0; i < this.list.length; i++) {
        if (
          this.list[i].calibration_num === "" ||
          this.list[i].calibration_num === null
        ) {
          ok = false;
          this.$message({
            type: "error",
            message: "请将实盘数填写完整,实盘数只能为整数",
          });
          break;
        }
        if (
          this.list[i].calibration_num < 0 ||
          !/^\d+$/.test(this.list[i].calibration_num)
        ) {
          ok = false;
          this.$message({ type: "error", message: "实盘数只能为整数" });
          break;
        }
      }
      if (ok) {
        this.infoText =
          type == 1
            ? "请将盘点仓库所有礼品库存核准,所有数据一经提交，当天不可再做修改"
            : "该操作为核准库存";
        this.url =
          type == 1 ? "/Stock_check/do_check" : "/Stock_check/calibration_save";
        this.$confirm(this.infoText, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.saveForm.store_id = this.formInline.store_id;
          this.saveForm.warehouse = this.formInline.warehouse;
          this.saveForm.house_id = this.formInline.house_id;
          this.saveForm.check_list = [];

          for (let i = 0; i < this.list.length; i++) {
            this.saveForm.check_list.push({
              remark: this.list[i].remark,
              gift_id: this.list[i].gift_id,
              check_num: this.list[i].calibration_num,
            });
          }
          if (type == 1) {
            this.is_save = true;
          }
          save(this.saveForm, this.url)
            .then((response) => {
              this.$message({
                type: response.code == 1 ? "success" : "error",
                message: response.message,
              });
              if (response.code == 1) {
                this.is_save = false;
                this.fetchData();
              }
            })
            .catch(() => {
              this.is_save = false;
            });
        });
      }
    },
    storeChange() {
      this.formInline.warehouse = "1";
    },
    warehouseChange(id) {
      if (id == 2) {
        this.getHouseList();
      }
    },
    exportClick() {
      getExport(this.formInline);
      this.exportLoading = true;
      this.$refs.cd.countDownF(30).then(() => {
        this.exportLoading = false;
      });
    },
    // 确定礼品
    saveGiftClick() {
      this.list.push(this.searchGiftList[0]);
      this.$message({ type: "success", message: "已添加到列表，请核准" });
      this.addGiftDialog = false;
    },
    addGiftClick() {
      this.addGiftDialog = true;
      this.searchGiftList = [];
    },
    searchGiftClick() {
      let ok = true;
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].gift_id == this.search_gift_no) {
          ok = false;
          this.$message({
            type: "error",
            message: "该礼品已存在于库存盘点界面请勿重复添加",
          });
          break;
        }
      }
      if (ok) {
        let data = {
          gift_no: this.search_gift_no,
          store_id: this.formInline.store_id,
          warehouse: this.formInline.warehouse,
          house_id: this.formInline.house_id,
        };
        this.listLoading = true;
        searchGift(data).then((response) => {
          if (response.length == 0) {
            this.$message({
              type: "error",
              message: "该礼品不存在于主仓（中转仓）中",
            });
          }
          response.forEach((val, i) => {
            val.imgList = [
              {
                src: val.img,
                msrc: val.thumb,
                w: 1200,
                h: 900,
              },
            ];
          });
          this.searchGiftList = response;
          this.listLoading = false;
        });
      }
    },
    searchClick() {
      this.warehouse = this.formInline.warehouse;
      if (this.formInline.store_id) {
        this.fetchData();
      } else {
        this.$message({ type: "error", message: "请选择门店" });
      }
    },
    getStoreList() {
      storeList({ category_id: 86 }).then((response) => {
        this.storeList = response;
        let data = response.filter(
          (res) => res.id == this.$store.getters.optionId
        );
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        } else {
          if (this.storeList.length > 0) {
            this.formInline.store_id = this.storeList[0].id;
          }
        }
      });
    },
    getHouseList() {
      houseList({ store_id: this.formInline.store_id }).then((response) => {
        this.houseList = response;
        if (this.houseList.length > 0) {
          this.formInline.house_id = response[0].house_id;
        } else {
          this.formInline.house_id = "";
        }
      });
    },
    // 列表获取
    fetchData() {
      this.no_save = true;
      this.no_check = true;
      this.listLoading = true;
      getList(this.formInline)
        .then((response) => {
          response.forEach((val, i) => {
            val.calibration_num =
              val.calibration_num == null ? "" : val.calibration_num;
            val.imgList = [
              {
                src: val.img,
                msrc: val.thumb,
                w: 1200,
                h: 900,
              },
            ];
          });
          this.list = response;
          if (response.length > 0) {
            this.no_save = response[0].calibration_num ? false : true;
            this.no_check = response[0].ok == 0 ? true : false;
          }
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
  },
};
</script>